package com.zhilei.controller;

import com.google.gson.Gson;
import com.zhilei.base.BaseInfoProperties;
import com.zhilei.enums.CompanyReviewStatus;
import com.zhilei.feign.UserInfoMicroServiceFeign;
import com.zhilei.grace.result.GraceJSONResult;
import com.zhilei.grace.result.ResponseStatusEnum;
import com.zhilei.intercept.JWTCurrentUserInterceptor;
import com.zhilei.pojo.Company;
import com.zhilei.pojo.CompanyPhoto;
import com.zhilei.pojo.Users;
import com.zhilei.pojo.bo.CreateCompanyBO;
import com.zhilei.pojo.bo.ModifyCompanyInfoBO;
import com.zhilei.pojo.bo.QueryCompanyBO;
import com.zhilei.pojo.bo.ReviewCompanyBO;
import com.zhilei.pojo.vo.CompanyInfoVO;
import com.zhilei.pojo.vo.CompanySimpleVO;
import com.zhilei.pojo.vo.UsersVO;
import com.zhilei.service.CompanyPhotoService;
import com.zhilei.service.CompanyService;
import com.zhilei.untils.JsonUtils;
import com.zhilei.untils.PagedGridResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;

/**
 * 企业微服务
 *
 * @author 志磊
 * @serial 2024-09-20
 */
@Slf4j
@RestController
@RequestMapping("company")
public class CompanyController extends BaseInfoProperties {

    @Autowired
    private CompanyService companyService;
    @Autowired
    private UserInfoMicroServiceFeign userInfoMicroServiceFeign;
    @Autowired
    private CompanyPhotoService companyPhotoService;

    /**
     * 根据公司名称查询公司是否存在
     *
     * @param fullName
     * @return
     */
    @PostMapping("getByFullName")
    public GraceJSONResult getByFullName(@RequestParam String fullName) {

        // TODO 校验公司名是否存在
        if (StringUtils.isBlank(fullName)) {
            return GraceJSONResult.exception(ResponseStatusEnum.COMPANY_INFO_UPDATED_ERROR);
        }

        // TODO 查询公司信息并返回
        Company company = companyService.getByFullName(fullName);

        // TODO 没有就直接返回一个null
        if (company == null) {
            return GraceJSONResult.ok(null);
        }

        // TODO 封装返回值并返回
        CompanySimpleVO companySimpleVO = new CompanySimpleVO();
        BeanUtils.copyProperties(company, companySimpleVO);

        return GraceJSONResult.ok(companySimpleVO);
    }

    /**
     * 创建公司
     *
     * @param createCompanyBO
     * @return
     */
    @PostMapping("createNewCompany")
    public GraceJSONResult createNewCompany(@RequestBody CreateCompanyBO createCompanyBO) {

        String companyId = createCompanyBO.getCompanyId();
        String newCompanyId = null;
        if (StringUtils.isBlank(companyId)) {
            newCompanyId = companyService.createNewCompany(createCompanyBO);
        } else {
            newCompanyId = companyService.resetCompany(createCompanyBO);
        }

        return GraceJSONResult.ok(newCompanyId);
    }

    /**
     * 根据企业id查询有多少位hr
     *
     * @param companyId
     * @param withHRCounts
     * @return
     */
    @PostMapping("getInfo")
    public GraceJSONResult getInfo(@RequestParam("companyId") String companyId, boolean withHRCounts) {

        CompanySimpleVO company = this.getCompany(companyId);
        if (company != null && withHRCounts) {
            // TODO 远程调用用户微服务，根据企业id查询hr的数量
            GraceJSONResult countsByCompanyId = userInfoMicroServiceFeign.getCountsByCompanyId(companyId);
            Object data = countsByCompanyId.getData();
            Long hrCount = Long.valueOf(data.toString());
            company.setHrCounts(hrCount);
        }

        return GraceJSONResult.ok(company);
    }

    /**
     * 提交审核信息进行审核
     *
     * @param reviewCompanyBO
     * @return
     */
    @PostMapping("goReviewCompany")
    public GraceJSONResult goReviewCompany(@RequestBody @Valid ReviewCompanyBO reviewCompanyBO) {

        // TODO 使用远程调用绑定企业与hr的关系
        String hrUserId = reviewCompanyBO.getHrUserId();
        String realname = reviewCompanyBO.getRealname();
        String companyId = reviewCompanyBO.getCompanyId();
        GraceJSONResult graceJSONResult = userInfoMicroServiceFeign.bindingHRToCompany(hrUserId, realname, companyId);
        String hrMobile = graceJSONResult.getData().toString();
        log.info("hrMobile: {}", hrMobile);

        reviewCompanyBO.setHrMobile(hrMobile);
        // TODO 审核通过后，提交申请信息到申请单表
        companyService.SubmitForReview(reviewCompanyBO);
        return GraceJSONResult.ok();
    }

    /**
     * 根据用户id查询最新的用户信息
     *
     * @param hrUserId
     * @return
     */
    @PostMapping("information")
    public GraceJSONResult information(@RequestParam("hrUserId") String hrUserId) {
        UsersVO hrUserInFoVo = this.getHRUserInFoVo(hrUserId);
        String hrInWhichCompanyId = hrUserInFoVo.getHrInWhichCompanyId();
        Company company = companyService.getHrInWhichCompany(hrInWhichCompanyId);
        return GraceJSONResult.ok(company);
    }

    /**
     * 抽取根据用户HRid获取最新企业的数据的方法
     *
     * @param hrUserId
     * @return
     */
    private UsersVO getHRUserInFoVo(String hrUserId) {
        GraceJSONResult hrUserInFo = userInfoMicroServiceFeign.get(hrUserId);
        // userVO
        Object hrUserInFoData = hrUserInFo.getData();

        String hrUserStr = JsonUtils.objectToJson(hrUserInFoData);
        return JsonUtils.jsonToPojo(hrUserStr, UsersVO.class);
    }

    /**
     * 根据企业id查询用户信息是否存在，先查询缓存
     *
     * @param companyId
     * @return
     */
    private CompanySimpleVO getCompany(String companyId) {
        if (StringUtils.isBlank(companyId)) {
            return null;
        }

        String companyJson = redis.get(REDIS_COMPANY_BASE_INFO + ":" + companyId);
        if (StringUtils.isBlank(companyJson)) {
            // 为空，查询数据库
            Company company = companyService.getById(companyId);
            if (company == null) {
                return null;
            }
            CompanySimpleVO companySimpleVO = new CompanySimpleVO();
            BeanUtils.copyProperties(company, companySimpleVO);

            redis.set(REDIS_COMPANY_BASE_INFO + ":" + companyId,
                    new Gson().toJson(companySimpleVO),
                    8 * 60 * 60);

            return companySimpleVO;
        } else {
            // 不为空，转换为对象
            return new Gson().fromJson(companyJson, CompanySimpleVO.class);
        }
    }

    /**
     * 查询企业审核列表数据
     *
     * @param asQueryCompany
     * @param page
     * @param limit
     * @return
     */
    @PostMapping("admin/getCompanyList")
    public GraceJSONResult getCompanyList(@RequestBody @Valid QueryCompanyBO asQueryCompany,
                                          @RequestParam("page") Integer page,
                                          @RequestParam("limit") Integer limit) {
        if (page == null) page = 1;
        if (limit == null) limit = 10;
        PagedGridResult companyList = companyService.getCompanyList(asQueryCompany, page, limit);
        return GraceJSONResult.ok(companyList);

    }

    /**
     * 根据企业id查询企业信息
     *
     * @param companyId
     * @return
     */
    @PostMapping("admin/getCompanyInfo")
    public GraceJSONResult getCompanyInfo(@RequestParam("companyId") String companyId) {
        Company company = companyService.getById(companyId);

        GraceJSONResult graceJSONResult = userInfoMicroServiceFeign.get(company.getCommitUserId());
        Object data = graceJSONResult.getData();
        String userVO = JsonUtils.objectToJson(data);
        UsersVO usersVO = JsonUtils.jsonToPojo(userVO, UsersVO.class);
        CompanyInfoVO companyInfoVO = new CompanyInfoVO();
        BeanUtils.copyProperties(company, companyInfoVO);
        log.error("usersVO.getRealName()； {}", usersVO.getRealName());
        companyInfoVO.setCommitUser(usersVO.getRealName());
        companyInfoVO.setCommitMobile(company.getCommitUserMobile());
        companyInfoVO.setCompanyId(companyId);

        return GraceJSONResult.ok(companyInfoVO);
    }

    /**
     * 审核企业
     *
     * @param reviewCompanyBO
     * @return
     */
    @PostMapping("admin/doReview")
    public GraceJSONResult doReview(@RequestBody @Valid ReviewCompanyBO reviewCompanyBO) {

        // TODO 审核企业
        companyService.updateReviewCompany(reviewCompanyBO);
        // TODO 审核成功后变更为HR角色
        if (Objects.equals(reviewCompanyBO.getReviewStatus(), CompanyReviewStatus.SUCCESSFUL.type)) {
            // 变更users表的数据
            userInfoMicroServiceFeign.updateHRRole(reviewCompanyBO.getHrUserId());
        }
        // TODO 清除缓存的数据
        redis.del(REDIS_COMPANY_BASE_INFO + ":" + reviewCompanyBO.getCompanyId());
        return GraceJSONResult.ok();
    }

    /**
     * saas 查询用户信息
     *
     * @return
     */
    @PostMapping("info")
    public GraceJSONResult info() {
        Users users = JWTCurrentUserInterceptor.USER_THREAD.get();
        CompanySimpleVO company = this.getCompany(users.getHrInWhichCompanyId());
        return GraceJSONResult.ok(company);
    }

    /**
     * saas端获取当前登录用户的企业信息
     *
     * @return
     */
    @PostMapping("saas/moreInfo")
    public GraceJSONResult saasMoreInfo() {
        Users users = JWTCurrentUserInterceptor.USER_THREAD.get();
        CompanyInfoVO companyInfoVO = getCompanyMoreVO(users.getHrInWhichCompanyId());
        return GraceJSONResult.ok(companyInfoVO);
    }

    /**
     * app端 查询用户信息
     *
     * @param companyId
     * @return
     */
    @PostMapping("moreInfo")
    public GraceJSONResult saasMoreInfo(@RequestParam("companyId") String companyId) {
        CompanyInfoVO companyInfoVO = getCompanyMoreVO(companyId);
        return GraceJSONResult.ok(companyInfoVO);
    }

    /**
     * app端维护企业信息
     *
     * @param modifyCompanyInfoBO
     * @return
     */
    @PostMapping("modify")
    public GraceJSONResult modify(@RequestBody @Valid ModifyCompanyInfoBO modifyCompanyInfoBO) {
        String companyId = modifyCompanyInfoBO.getCompanyId();
        String commitUserId = modifyCompanyInfoBO.getCurrentUserId();
        log.debug("commitUserId； {}", commitUserId);

        UsersVO hrUserInFoVo = getHRUserInFoVo(commitUserId);
        if (!hrUserInFoVo.getHrInWhichCompanyId().equalsIgnoreCase(companyId)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.COMPANY_INFO_UPDATED_ERROR);
        }

        // TODO 修改企业的简称
        companyService.updateCompanyShortName(modifyCompanyInfoBO);

        String photos = modifyCompanyInfoBO.getPhotos();
        if (StringUtils.isNotBlank(photos)) {
            companyPhotoService.savePhoto(companyId, photos);
        }

        return GraceJSONResult.ok();
    }

    /**
     * app端根据企业id获取图片
     *
     * @param companyId
     * @return
     */
    @PostMapping("getPhotos")
    public GraceJSONResult getPhotos(@RequestParam("companyId") String companyId) {
        if (StringUtils.isBlank(companyId))
            return GraceJSONResult.error();
        CompanyPhoto companyPhotos = companyService.getCompanyPhotos(companyId);
        return GraceJSONResult.ok(companyPhotos);
    }

    /**
     * saas端查询企业相册
     *
     * @param
     * @return
     */
    @PostMapping("saas/getPhotos")
    public GraceJSONResult getSaasPhotos() {
        String companyId = JWTCurrentUserInterceptor.USER_THREAD.get().getHrInWhichCompanyId();
        if (StringUtils.isBlank(companyId))
            return GraceJSONResult.error();
        CompanyPhoto companyPhotos = companyService.getCompanyPhotos(companyId);
        return GraceJSONResult.ok(companyPhotos);
    }

    /**
     * 根据企业id查询企业信息并返回
     *
     * @param companyId
     * @return
     */
    private CompanyInfoVO getCompanyMoreVO(String companyId) {
        if (StringUtils.isBlank(companyId)) {
            return null;
        }

        String companyJson = redis.get(REDIS_COMPANY_MORE_INFO + ":" + companyId);
        if (StringUtils.isBlank(companyJson)) {
            // 为空，查询数据库
            Company company = companyService.getById(companyId);
            log.error("Company: {}", company);
            if (company == null) {
                return null;
            }
            CompanyInfoVO companyInfoVO = new CompanyInfoVO();
            BeanUtils.copyProperties(company, companyInfoVO);
            companyInfoVO.setCompanyId(companyId);

            redis.set(REDIS_COMPANY_MORE_INFO + ":" + companyId,
                    new Gson().toJson(companyInfoVO),
                    8 * 60 * 60);

            return companyInfoVO;
        } else {
            // 不为空，转换为对象
            return new Gson().fromJson(companyJson, CompanyInfoVO.class);
        }
    }

}
